package cn.sz.dzy.io.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.stream.Collectors;

/**
 * @program: io
 * @description:
 * @author: DingZhenYun
 * @create: 2024-05-24 11:22
 **/

public class ServerReaderThread extends Thread{
    private Socket socket;
    public ServerReaderThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        // 1、从socket中去获取当前客户端的输入流
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg ;
            while ((msg=bufferedReader.readLine())!=null){
                // 2、服务端接收到了客户端的消息之后，是需要推送给当前所有的在线socket
                System.out.println("服务端收到信息:"+msg);
                sendMsgToAllClient(msg,socket);
            }
        } catch (Exception e) {
            System.out.println("当前有人下线了！");
            // 从在线socket集合中移除本socket
            Server.allSocketOnLine.remove(socket);
        }
    }


    /**
     * 把当前客户端发来的消息推送给其他在线的socket
     * @param msg
     */
    private void sendMsgToAllClient(String msg,Socket socket) throws Exception {
//        for (Socket sk : Server.allSocketOnLine) {
//            if(!sk.equals(socket)){
//                PrintStream ps = new PrintStream(sk.getOutputStream());
//                ps.println(msg);
//                ps.flush();
//            }
//        }
        Server.allSocketOnLine.stream().filter(e->{
            return !socket.equals(e);
        }).collect(Collectors.toList()).stream().forEach(e->{
            try {
                PrintStream ps = new PrintStream(e.getOutputStream());
                ps.println(msg);
                ps.flush();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
    }
}
